package org.djustice.apkgot;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class BatchDownloadActivity extends Activity implements Runnable {

    private TextView output;
    private Button go_button;
    private ProgressBar progress;

    private Thread thread;

    private String apkList;
    private String pageUrlList;

    private int start_int;
    private int stop_int;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	setTitle("apkGot");
	setContentView(R.layout.batch_download);

	TextView tv = (TextView) findViewById(R.id.batch_download_site_textView);
	tv.setText("apkTop");

	go_button = (Button) findViewById(R.id.batch_download_go_Button);
	go_button.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View v) {
		EditText start = (EditText) findViewById(R.id.batch_download_start_textView);
		EditText stop = (EditText) findViewById(R.id.batch_download_stop_textView);

		start_int = Integer.parseInt(start.getText().toString());
		stop_int = Integer.parseInt(stop.getText().toString());

		progress = (ProgressBar) findViewById(R.id.progressBar1);
		progress.setMax(stop_int * 10);

		thread = new Thread(BatchDownloadActivity.this);
		thread.start();

		output.setText("");
	    }
	});
	
	apkList = "";
	pageUrlList = "";

	output = (TextView) findViewById(R.id.batch_download_output_textView);
//	output.setMovementMethod(new ScrollingMovementMethod());
    }

    @Override
    public void run() {
	Looper.prepare();
	
	if (!isNetworkAvailable())
	    finish();

	for (int i = start_int; i <= stop_int; i++) {
	    String page = "http://apktop.com/page/" + i + "\n";
	    fetchPageDataTask task = new fetchPageDataTask();

	    System.out.println("feep: " + i);

	    task.doInBackground(page);

	    int j = 0;
	    for (String pageUrl : pageUrlList.split("\n")) {
		parsePageDataTask parse_task = new parsePageDataTask();
		String x = parse_task.doInBackground(pageUrl);

		if (x == "") {

		} else {
		    downloadFileTask download_task = new downloadFileTask();
		    download_task.doInBackground(x + ":::" + pageUrl.split(".com/")[1].replace(".html", ".apk"));
		}

		Message msg_d = new Message();
		Bundle bundle_d = new Bundle();
		String m = i + "" + j;
		int n = Integer.decode(m);
		bundle_d.putString("message", "" + (n - 9) + ": " + pageUrl.split(".com/")[1].replace(".html", ".apk"));
		msg_d.setData(bundle_d);
		handler.sendMessage(msg_d);

		progress.setProgress(progress.getProgress() + 1);

		j++;
	    }

	    pageUrlList = "";
	}
    }

    private Handler handler = new Handler() {
	@Override
	public void handleMessage(Message msg) {
	    output.setText(output.getText() + "\n" + msg.getData().getString("message"));
	}
    };

    private class fetchPageDataTask extends AsyncTask<String, Void, String> {

	@Override
	protected String doInBackground(String... urls) {

	    String pageData = "";

	    for (String url : urls) {

		try {
		    URL updateURL = new URL(url);
		    URLConnection conn = updateURL.openConnection();
		    InputStream is = conn.getInputStream();
		    BufferedInputStream bis = new BufferedInputStream(is);
		    ByteArrayBuffer baf = new ByteArrayBuffer(50);

		    int current = 0;
		    while((current = bis.read()) != -1){
			baf.append((byte)current);
		    }

		    String html = new String(baf.toByteArray());
		    for (String line : html.split("\n") ) {
			pageData = pageData + "\n" + line;
			if (line.contains("<h2>") && line.contains(".html")) {
			    pageUrlList = pageUrlList + 
				    line.substring(19).substring(0, 
					    line.substring(19).indexOf("\" rel")) + "\n";
			    System.out.println(line);
			}
		    }
		} catch (Exception e) {
		    System.out.println("\n!! failed to load page.. connection issues?\n" + e.getMessage());
		}
	    }

	    return pageData;
	}
    }

    private class parsePageDataTask extends AsyncTask<String, Void, String> {
	private String output = "";

	@Override
	protected String doInBackground(String... page) {
	    try {
		URL u = new URL(page[0]);
		URLConnection yc = u.openConnection();
		BufferedReader in = new BufferedReader(
			new InputStreamReader(yc.getInputStream()));

		String inputLine;

		while ((inputLine = in.readLine()) != null) {
		    if (inputLine.contains("a href") && inputLine.contains("download-monitor")) {
			output = output + inputLine.substring(9, inputLine.indexOf("\" tit")) + "\n";
		    }
		}

		in.close();
	    } catch (Exception e) {
		System.out.println("\n!! failed to load page " + page + ".. connection issues?\n" + e.getMessage());
	    }

	    return output;
	}
    }

    private class downloadFileTask extends AsyncTask<String, Void, String> {
	@Override
	protected String doInBackground(String... paths) {
	    try {
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    File path = Environment.getExternalStoragePublicDirectory(
			    Environment.DIRECTORY_DOWNLOADS);
		    path.mkdir();
		    File apkPath = new File(path, "/apkGet");
		    apkPath.mkdir();
		    File file = new File(apkPath, paths[0].split(":::")[1]);

		    BufferedInputStream in = new BufferedInputStream(new URL(paths[0].split(":::")[0]).openStream());
		    FileOutputStream fos = new FileOutputStream(file);
		    BufferedOutputStream bout = new BufferedOutputStream(fos,1024);

		    byte data[] = new byte[1024];

		    int x = 0;
		    while((x = in.read(data,0,1024)) >= 0) {
			bout.write(data, 0, x);
		    }

		    bout.close();
		    in.close();
		}
	    } catch (Exception e) {
		System.out.println("\n!! failed to download, " + paths[0].split(":::")[1]);
	    }

	    return "";
	}
    }

    public boolean isNetworkAvailable() {
	Context context = getApplicationContext();
	ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	if (connectivity == null) {
	    AlertDialog.Builder alert = new AlertDialog.Builder(this);

	    alert.setTitle("Title");
	    alert.setMessage("No connection");

	    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int whichButton) { }
	    });

	    alert.show();
	} else {
	    NetworkInfo[] info = connectivity.getAllNetworkInfo();
	    if (info != null) {
		for (int i = 0; i < info.length; i++) {
		    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
			return true;
		    }
		}
	    }
	}
	return false;
    }
}

